/*
  Applicast API Extension/Utility Library
  List view component

  (c) 2009 ILERRED, S.L.

  Applicast API Extension Library is freely
  distributable under the terms of an MIT-style license.
*/
var ListView = Class.create({
  initialize: function(options) {
    this.options = {
      sourceList: [],
      maxElements: 3
    };
    Object.extend(this.options, options || { });

    this.list = $A(this.options.sourceList);
    this.size = this.list.length;

    this.selected = 0;
    this.move = 0;
    this.max = this.options.maxElements;
    this.start = 0;
  },

  // Child views should implement show && highlightSelected methods

  first: function() {
    this.start = 0;
    this.move = 0;
    this.selected = 0;

    this.update();
  },

  last: function() {
    this.move = this.max - 1;
    this.selected = this.size - 1;
    this.start = ((this.selected < this.max) ? 0 : (this.selected - this.max) + 1);

    this.update();
  },

  next: function() {
    this.move++;

    this.selected++;
    if ( this.selected >= this.size )
      this.selected = this.size - 1;

    if ( this.move > this.max-1 ) {
      this.start = ((this.selected < this.max) ? 0 : (this.selected - this.max) + 1);
      this.move = this.max - 1;
      if ( typeof this.show !== 'undefined' )
        this.show(this.start);
    }
    if ( typeof this.highlightSelected !== 'undefined' )
      this.highlightSelected();
  },

  prev: function() {
    this.move--;

    this.selected--;
    if ( this.selected < 0 )
      this.selected = 0;

    if ( this.move < 0 ) {
      this.start = this.selected;
      this.move = 0;
      if ( typeof this.show !== 'undefined' )
        this.show(this.start);
    }
    if ( typeof this.highlightSelected !== 'undefined' )
      this.highlightSelected();
  },

  moveToIndex: function(index) {
    if ( index < 0 ) index = 0;
    else if ( index >= this.size ) index = this.size - 1;

    this.selected = index;
    this.move = ((this.selected + this.max < this.size) ? 0 : this.max - (this.size - this.selected));
    this.start = ((this.selected + this.max) < this.size ? this.selected : this.size - this.max);

    this.update();
  },

  update: function() {
    if ( typeof this.show !== 'undefined' )
      this.show(this.start);

    if ( typeof this.highlightSelected !== 'undefined' )
      this.highlightSelected();
  },

  selectedIndex: function() {
    return this.selected;
  },

  getSelected: function() {
    return Object.clone(this.list[this.selected]);
  },

  asArray: function() {
    return $A(Object.clone(this.list));
  },

  // for fast node access
  // Node class performs quite an overhead here...
  _get$: function(node) {
    if ( typeof node === 'string' ) return getNode(node);
    return node;
  }
});